﻿using CanDoo.Data;
using CanDoo.Filter;
using CanDoo.Oil.Core.DTOs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace CanDooOSS
{
    public class MediaApiService
    {
        private string clientId = "6677";
        private string clientSecret = "1";

        private HttpClient _httpClient;

        public string ServerBaseAddress { get; set; }

        public MediaApiService(string serverBaseAddress)
        {
            ServerBaseAddress = serverBaseAddress;

            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(ServerBaseAddress);
        }

        public async Task<PageResult<MediaInfo>> DoGet()
        {
            //CardNoStart=20160180&CardNoEnd=20160183
            var path = string.Format("/api/pad/PullMediaList");
            HttpContent content = new StringContent("");
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await _httpClient.PostAsync(path, content);
            if (response != null)
            {
                if (response.IsSuccessStatusCode)
                {
                    var responseValue = await response.Content.ReadAsStringAsync();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<PageResult<MediaInfo>>(responseValue);
                }
            }
            return await Task.FromResult(new PageResult<MediaInfo>());
        }

        public async Task<ApiResult> DoPost(MediaInfo info)
        {
            var url = "/api/Media";
            var strEncodeBody = JsonConvert.SerializeObject(info);
            HttpContent content = new StringContent(strEncodeBody);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await _httpClient.PostAsync(url, content);
            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var resultValue = await response.Content.ReadAsStringAsync();

                    return Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResult>(resultValue); ;
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var resultValue = await response.Content.ReadAsStringAsync();
                    try
                    {
                        return Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResult>(resultValue);
                    }
                    catch (Exception ex)
                    {
                        return new ApiResult(ApiResultType.error,"操作发生异常",null,ex.Message);
                    }
                }
            }

            return await Task.FromResult<ApiResult>(new ApiResult(ApiResultType.fail, "系统没有回应"));
        }

    }
}
